import React, { Component } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import ScrollSelect from '@/components/ScrollSelect';
import IconButton from '@/components/IconButton';
import { Row, Col, Form, Input, Tabs, Select, Card, Button, DatePicker, message } from 'antd';

import { connect } from 'dva';
import api from '@/api';
import get from 'lodash/get';
import moment from 'moment';
import { maxLength } from '@/utils/form';
import { stringify } from 'querystring';
import isEmpty from 'lodash/isEmpty';
import numeral from 'numeral';
import styles from './ProfitShare.less';

const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;

@Form.create()
@connect(({ loading, dashboard }) => ({
  totalLoading: loading.effects['dashboard/fetchProfileShareTotal'],
  detailLoading: loading.effects['dashboard/fetchProfileShareDetail'],
}))
class ProfitShare extends Component {
  state = {
    profileShareTotals: {
      list: [],
      pagination: {},
    },
    profileShareDetails: {
      list: [],
      pagination: {},
    },
    tabType: 1,
    searchTotalParams: {},
    searchDetailParams: {},
    detailCount: 0,
    feeType: [
      { code: '揽收费', name: '揽收费' },
      { code: '空运费', name: '空运费' },
      { code: '提货费', name: '提货费' },
      { code: '配送费', name: '配送费' },
      { code: '货值保障服务费', name: '货值保障服务费' },
    ],
  };
  columns = [
    {
      title: '序号',
      render: (text, record, index) => {
        return <span>{this.calcIndex(index)}</span>;
      },
      width: 100,
    },
    {
      title: '供应商',
      dataIndex: 'supplierName',
    },
    {
      title: '订单金额(CNY)',
      dataIndex: 'sumOrderAmount',
      align: 'right',
      width: '7%',
      render: (text, record, index) => {
        return <span>{numeral(text).format('0,000.00')}</span>;
      },
    },
    {
      title: '',
      width: '6%',
    },
    {
      title: '费用项',
      dataIndex: 'feeItem',
    },
    {
      title: '销售金额(CNY)',
      dataIndex: 'sumSaleFeeAmount',
      align: 'right',
      render: (text, record, index) => {
        return <span>{numeral(text).format('0,000.00')}</span>;
      },
    },
    // {
    //   title: '实付金额(CNY)',
    //   dataIndex: 'sumSaleActualFeeAmount',
    //   align: 'right',
    //   render: (text, record, index) => {
    //     return <span>{numeral(text).format('0,000.00')}</span>;
    //   },
    // },

    {
      title: '成本金额(CNY)',
      dataIndex: 'sumCostFeeAmount',
      align: 'right',
      render: (text, record, index) => {
        return <span>{numeral(text).format('0,000.00')}</span>;
      },
    },
    {
      title: '利润(CNY)',
      dataIndex: 'sumFeeGrossProfit',
      align: 'right',
      render: (text, record, index) => {
        return <span>{numeral(text).format('0,000.00')}</span>;
      },
    },
    {
      title: '供应商分成(CNY)',
      dataIndex: 'sumSupplierProfitAmount',
      align: 'right',
      render: (text, record, index) => {
        return <span>{numeral(text).format('0,000.00')}</span>;
      },
    },
    {
      title: '平台分成(CNY)',
      dataIndex: 'sumProfitAmount',
      align: 'right',
      render: (text, record, index) => {
        return <span>{numeral(text).format('0,000.00')}</span>;
      },
    },
  ];
  columns2 = [
    {
      title: '序号',
      render: (text, record, index) => {
        return <span>{this.calcIndex2(index)}</span>;
      },
      width: 100,
    },
    {
      title: '供应商',
      dataIndex: 'supplierName',
    },
    {
      title: '订单号',
      dataIndex: 'waybillNo',
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatusName',
    },
    {
      title: '订单金额(CNY)',
      dataIndex: 'orderAmount',
      align: 'right',
      width: '7%',
      render: (text, record, index) => {
        return <span>{numeral(text).format('0,000.00')}</span>;
      },
    },
    {
      title: '',
      width: '6%',
    },
    {
      title: '费用项',
      dataIndex: 'feeItem',
    },
    {
      title: '销售金额(CNY)',
      dataIndex: 'saleFeeAmount',
      align: 'right',
      render: (text, record, index) => {
        return <span>{numeral(text).format('0,000.00')}</span>;
      },
    },
    // {
    //   title: '实付金额(CNY)',
    //   dataIndex: 'actualSaleFeeAmount',
    //   align: 'right',
    //   render: (text, record, index) => {
    //     return <span>{numeral(text).format('0,000.00')}</span>;
    //   },
    // },

    {
      title: '成本金额(CNY)',
      dataIndex: 'costFeeAmount',
      align: 'right',
      render: (text, record, index) => {
        return <span>{numeral(text).format('0,000.00')}</span>;
      },
    },
    {
      title: '利润(CNY)',
      dataIndex: 'feeGrossProfit',
      align: 'right',
      render: (text, record, index) => {
        return <span>{numeral(text).format('0,000.00')}</span>;
      },
    },
    {
      title: '供应商分成(CNY)',
      dataIndex: 'supplierProfitAmount',
      align: 'right',
      render: (text, record, index) => {
        return <span>{numeral(text).format('0,000.00')}</span>;
      },
    },
    {
      title: '平台分成(CNY)',
      dataIndex: 'profitAmount',
      align: 'right',
      render: (text, record, index) => {
        return <span>{numeral(text).format('0,000.00')}</span>;
      },
    },
    {
      title: '',
      width: '6%',
    },
    {
      title: '订单日期',
      dataIndex: 'orderCreateTime',
    },
    {
      title: '完成时间',
      dataIndex: 'finishedTime',
    },
  ];
  calcIndex = index => {
    const { profileShareTotals } = this.state;
    let currentPage = get(profileShareTotals, 'pagination.currentPage') || 1;
    let pageSize = get(profileShareTotals, 'pagination.pageSize') || 50;
    return (currentPage - 1) * pageSize + index + 1;
  };
  calcIndex2 = index => {
    const { profileShareDetails } = this.state;
    let currentPage = get(profileShareDetails, 'pagination.currentPage') || 1;
    let pageSize = get(profileShareDetails, 'pagination.pageSize') || 50;
    return (currentPage - 1) * pageSize + index + 1;
  };
  componentDidMount() {
    this.queryProfileShareTotal();
  }
  // 汇总查询
  queryProfileShareTotal = ({ pageIndex = 1, pageSize = 50 } = {}) => {
    const {
      form: { validateFields },
      dispatch,
    } = this.props;
    validateFields((err, value) => {
      let params = {
        pageIndex,
        pageSize,
      };
      if (value.supplierId) {
        params = { ...params, supplierId: value.supplierId.key };
      }
      if (value.date && value.date.length === 2) {
        params = {
          ...params,
          signedStartTime: value.date[0].startOf('day').format('YYYY-MM-DD 00:00:00'),
          signedEndTime: value.date[1].startOf('day').format('YYYY-MM-DD 23:59:59'),
        };
      }
      dispatch({
        type: 'dashboard/fetchProfileShareTotal',
        payload: {
          queryParams: params,
        },
      }).then(({ errorCode, data, pagination }) => {
        if (errorCode === 0) {
          this.setState({
            profileShareTotals: { list: data, pagination },
            searchTotalParams: params,
          });
        }
      });
    });
  };
  // 明细查询
  queryProfileShareDetail = ({ pageIndex = 1, pageSize = 50 } = {}) => {
    const {
      form: { validateFields },
      dispatch,
    } = this.props;
    validateFields((err, value) => {
      let params = {
        pageIndex,
        pageSize,
      };
      if (value.supplierId) {
        params = { ...params, supplierId: value.supplierId.key };
      }
      if (value.waybillNo) {
        params = { ...params, waybillNo: value.waybillNo };
      }
      if (value.feeItem) {
        params = { ...params, feeItem: value.feeItem };
      }
      if (value.date && value.date.length === 2) {
        params = {
          ...params,
          signedStartTime: value.date[0].startOf('day').format('YYYY-MM-DD 00:00:00'),
          signedEndTime: value.date[1].startOf('day').format('YYYY-MM-DD 23:59:59'),
        };
      }

      dispatch({
        type: 'dashboard/fetchProfileShareDetail',
        payload: {
          queryParams: params,
        },
      }).then(({ errorCode, data, pagination }) => {
        if (errorCode === 0) {
          this.setState({
            profileShareDetails: { list: data, pagination },
            searchDetailParams: params,
          });
        }
      });
      dispatch({
        type: 'dashboard/fetchProfileShareDetailCount',
        payload: {
          queryParams: params,
        },
      }).then(({ errorCode, data }) => {
        if (errorCode === 0) {
          this.setState({ detailCount: data });
        }
      });
    });
  };
  // 汇总分页
  handleTotalTableChange = pagination => {
    const { current: pageIndex, pageSize } = pagination;
    let params = { pageIndex, pageSize };
    this.queryProfileShareTotal(params);
  };
  // 汇总重置
  handleReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.queryProfileShareTotal();
  };
  // 明细重置
  handleDetailReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.queryProfileShareDetail();
  };
  // 明细分页
  handleDetailTableChange = pagination => {
    let params = { pageIndex: pagination.current, pageSize: pagination.pageSize };
    this.queryProfileShareDetail(params);
  };
  // 查询供应商
  querySuppliers = params => {
    return api.supplier.shortQuery({
      queryParams: params,
    });
  };

  // tab转换
  handleChangeTab = val => {
    this.setState({
      tabType: val,
    });
    val === '1' ? this.queryProfileShareTotal() : this.queryProfileShareDetail();
  };

  exportDetail = () => {
    const { detailCount, searchDetailParams } = this.state;
    if (detailCount > 60000) {
      message.warning('明细条数超过6万条,禁止导出');
      return;
    }
    let exportUrl = `/api/v1/profit/share/detail/list/down`;
    if (!isEmpty(searchDetailParams)) {
      let query = {
        supplierId: searchDetailParams.supplierId,
        feeItem: searchDetailParams.feeItem,
        waybillNo: searchDetailParams.waybillNo,
        signedStartTime: searchDetailParams.signedStartTime,
        signedEndTime: searchDetailParams.signedEndTime,
      };
      exportUrl = `/api/v1/profit/share/detail/list/down?${stringify(query)}`;
    }
    let a = document.createElement('a');
    a.target = '_blank';
    a.href = exportUrl;
    a.click();
  };
  // 汇总
  renderTotalTabContent = () => {
    const {
      totalLoading,
      form: { getFieldDecorator },
    } = this.props;
    const { profileShareTotals, searchTotalParams } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };
    let exportUrl = `/api/v1/profit/share/sum/list/down`;
    if (!isEmpty(searchTotalParams)) {
      let query = {
        supplierId: searchTotalParams.supplierId,
        signedStartTime: searchTotalParams.signedStartTime,
        signedEndTime: searchTotalParams.signedEndTime,
      };
      exportUrl = `/api/v1/profit/share/sum/list/down?${stringify(query)}`;
    }
    return (
      <>
        <div className={styles.search}>
          <Form {...formItemLayout}>
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col md={8} sm={24}>
                <FormItem label="供&ensp;应&ensp;商">
                  {getFieldDecorator('supplierId')(
                    <ScrollSelect
                      allowClear
                      search={this.querySuppliers}
                      style={{ width: '100%' }}
                      onInput={e => maxLength(e, 15)}
                      placeholder="请输入供应商或编码"
                      optionLabel="name"
                      optionKey="id"
                    />
                  )}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <FormItem label="完成日期">
                  {getFieldDecorator('date', {
                    initialValue: [
                      moment()
                        .startOf('day')
                        .subtract(30, 'days'),
                      moment().endOf('day'),
                    ],
                  })(
                    <RangePicker
                      allowClear={false}
                      style={{ width: '100%' }}
                      format="YYYY-MM-DD"
                      placeholder={['开始日期', '结束日期']}
                    />
                  )}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <Button onClick={this.handleReset}>重置</Button>
                <Button type="primary" onClick={this.queryProfileShareTotal}>
                  查询
                </Button>
              </Col>
            </Row>
          </Form>
        </div>
        {profileShareTotals.list.length > 0 && (
          <div className={styles.tableListOperator} style={{ minHeight: 32 }}>
            <a href={exportUrl} target="_blank">
              <IconButton title="导出" icon="icon-export" />
            </a>
          </div>
        )}
        <StandardTable
          rowKey="id"
          loading={totalLoading}
          data={profileShareTotals}
          columns={this.columns}
          onChange={this.handleTotalTableChange}
        />
      </>
    );
  };
  // 明细
  renderTetailTabContent = () => {
    const {
      detailLoading,
      form: { getFieldDecorator },
    } = this.props;
    const { profileShareDetails, searchDetailParams, detailCount, feeType } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };

    return (
      <>
        <div className={styles.search}>
          <Form {...formItemLayout}>
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col md={8} sm={24}>
                <FormItem label="订&ensp;单&ensp;号">
                  {getFieldDecorator('waybillNo', {
                    normalize: (value, prevValue) => {
                      return value && value.replace(/\s*/g, '');
                    },
                  })(<Input style={{ width: '100%' }} maxLength={20} />)}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <FormItem label="供&ensp;应&ensp;商">
                  {getFieldDecorator('supplierId')(
                    <ScrollSelect
                      allowClear
                      search={this.querySuppliers}
                      style={{ width: '100%' }}
                      onInput={e => maxLength(e, 15)}
                      placeholder="请输入供应商或编码"
                      optionLabel="name"
                      optionKey="id"
                    />
                  )}
                </FormItem>
              </Col>

              <Col md={8} sm={24}>
                <FormItem label="费&ensp;用&ensp;项">
                  {getFieldDecorator('feeItem')(
                    <Select style={{ width: '100%' }} placeholder="请选择费用项" allowClear>
                      {feeType.map(item => (
                        <Option value={item.code} key={item.id}>
                          {item.name}
                        </Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col md={8} sm={24}>
                <FormItem label="完成日期" {...formItemLayout}>
                  {getFieldDecorator('date', {
                    initialValue: [
                      moment()
                        .startOf('day')
                        .subtract(30, 'days'),
                      moment().endOf('day'),
                    ],
                  })(
                    <RangePicker
                      allowClear={false}
                      style={{ width: '100%' }}
                      format="YYYY-MM-DD"
                      placeholder={['开始日期', '结束日期']}
                    />
                  )}
                </FormItem>
              </Col>
              <Col md={8} sm={24} offset={8}>
                <Button onClick={this.handleDetailReset}>重置</Button>
                <Button type="primary" onClick={this.queryProfileShareDetail}>
                  查询
                </Button>
              </Col>
            </Row>
          </Form>
        </div>
        {profileShareDetails.list.length > 0 && (
          <div className={styles.tableListOperator} style={{ minHeight: 32 }}>
            <IconButton
              title="导出"
              icon="icon-export"
              onClick={this.exportDetail}
              style={{ color: '#1890FF' }}
            />
          </div>
        )}
        <StandardTable
          rowKey="id"
          loading={detailLoading}
          data={profileShareDetails}
          columns={this.columns2}
          onChange={this.handleDetailTableChange}
        />
      </>
    );
  };

  render() {
    const { tabType } = this.state;
    const type = `${tabType}`;
    return (
      <PageHeaderWrapper title="利润分成">
        <Card bordered={false}>
          <Tabs defaultActiveKey="1" activeKey={type} onChange={this.handleChangeTab}>
            <TabPane key="1" tab="汇总">
              {this.renderTotalTabContent()}
            </TabPane>
            <TabPane key="2" tab="明细">
              {this.renderTetailTabContent()}
            </TabPane>
          </Tabs>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default ProfitShare;
